package com.erb.task;

import com.erb.common.Constant;
import com.erb.constants.AdminInformConstants;
import com.erb.constants.AdminProductConstants;
import com.erb.constants.InvestConstants;
import com.erb.entity.CapitalLog;
import com.erb.entity.Inform;
import com.erb.entity.Invest;
import com.erb.entity.Product;
import com.erb.service.llb.IOtherService;
import com.erb.service.llb.InvestService;
import com.erb.service.zwj.IInformService;
import com.erb.service.zwj.IProductService;
import com.erb.utils.BigDecimalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 投资收益定时任务
 */
@Component
public class ProfitTask {

	@Autowired
	InvestService investService;
	@Autowired
	IProductService productService;
	@Autowired
	IOtherService otherService;
	@Autowired
	IInformService informService;

	@Scheduled(cron = "0 0/5 * * * ?")
	public void profit() {
		//所有招标中的投资 更新招标中的投资为回款中
		investService.batchUpdateStatus(InvestConstants.INVEST_STATUS_INBIDDING, InvestConstants.INVEST_STATUS_RETURN);
        /*List<Invest> inbidding_invests = investService.findByStatus(InvestConstants.INVEST_STATUS_INBIDDING);
        inbidding_invests.forEach(invest -> {
            //投资的项目
            Product product = productService.findProductById(invest.getPid());
            //如果是平台标
            if (product.getType() != AdminProductConstants.PRODUCT_TYPE_CONVERSION_LOAN) {
                //把该投资改为回款中
                investService.updateStatus(invest.getId(), InvestConstants.INVEST_STATUS_RETURN);
            }
        });*/
		//所有回款中的投资
		List<Invest> return_invests = investService.findByStatus(InvestConstants.INVEST_STATUS_RETURN);
		return_invests.forEach(invest -> {
			//投资的项目
			Product product = productService.findProductById(invest.getPid());
			//现在时间戳
			Long now = System.currentTimeMillis();
			//交易金额
			Double tradeMoney = null;
			//消息
			String msg = null;
			//投资时间
			Long startTime;
			//资金记录类型
			int type = 0;
			Calendar calendar;
			//投资时间已过
			if (invest.getEndDate().getTime() <= now) {
				switch (product.getRepayType()) {
					//到期还本付息
					case AdminProductConstants.PRODUCT_REPAY_TYPE_END:
						tradeMoney = invest.getInvestMoney() + invest.getProfit();
						type = Constant.INTEREST_RETURN_BALANCE;
						msg = "您购买的投资项目[" + product.getPname() + "]已到期，返回本金" + invest.getInvestMoney() + "元，利息" + invest.getProfit() + "元。请注意查收！";
						break;
					//按月付息 到期还本
					case AdminProductConstants.PRODUCT_REPAY_TYPE_END_MONTH:
						tradeMoney = invest.getInvestMoney() + invest.getProfit() / invest.getLockDate();
						type = Constant.PRINCIPAL_RETURN_BALANCE;
						msg = "您购买的投资项目[" + product.getPname() + "]已到期，返回本金" + invest.getInvestMoney() + "元，利息" + BigDecimalUtil.formatDouble(invest.getProfit() / invest.getLockDate()) + "元。请注意查收！";
						break;
					//等额本息
					case AdminProductConstants.PRODUCT_REPAY_TYPE_MONTH:
						tradeMoney = (invest.getProfit() + invest.getInvestMoney()) / invest.getLockDate();
						type = Constant.INTEREST_RETURN_BALANCE;
						msg = "您购买的投资项目[" + product.getPname() + "]已到期，返回本息" + BigDecimalUtil.formatDouble(tradeMoney) + "元";
						break;
					default:
						break;
				}
				investService.updateStatus(invest.getId(), InvestConstants.INVEST_STATUS_FINISHED);
			} else {
				switch (product.getRepayType()) {
					//按月付息 到期还本
					case AdminProductConstants.PRODUCT_REPAY_TYPE_END_MONTH:
						startTime = invest.getInvestDate().getTime();
						calendar = Calendar.getInstance();
						if (invest.getLastProfitDate() == null) {
							calendar.setTimeInMillis(startTime);
						} else {
							calendar.setTimeInMillis(invest.getLastProfitDate().getTime());
						}
						calendar.add(Calendar.MONTH, 1);
						if (now >= calendar.getTimeInMillis()) {
							tradeMoney = invest.getProfit() / invest.getLockDate();
							type = Constant.INTEREST_RETURN_BALANCE;
							msg = "您购买的投资项目[" + product.getPname() + "]已到一个月，返回利息" + BigDecimalUtil.formatDouble(tradeMoney) + "元";
						}
						break;
					//等额本息
					case AdminProductConstants.PRODUCT_REPAY_TYPE_MONTH:
						startTime = invest.getInvestDate().getTime();
						calendar = Calendar.getInstance();
						if (invest.getLastProfitDate() == null) {
							calendar.setTimeInMillis(startTime);
						} else {
							calendar.setTimeInMillis(invest.getLastProfitDate().getTime());
						}
						calendar.add(Calendar.MONTH, 1);
						if (now >= calendar.getTimeInMillis()) {
							tradeMoney = (invest.getProfit() + invest.getInvestMoney()) / invest.getLockDate();
							type = Constant.INTEREST_RETURN_BALANCE;
							msg = "您购买的投资项目[" + product.getPname() + "]已到一个月，返回本息" + BigDecimalUtil.formatDouble(tradeMoney) + "元";
						}
						break;
					default:
						break;
				}
			}
			if (tradeMoney != null) {
				tradeMoney = BigDecimalUtil.formatDouble(tradeMoney);
				//更新最后一次收益时间
				investService.updateLastProfitDate(invest.getId(), new Timestamp(now));
				//添加资金记录
				addCapitalLog(invest.getUid(), tradeMoney, invest.getPid(), type);
				//添加用户余额
				upadteUserBalance(invest.getUid(), tradeMoney);
				//发送消息
				sendMsg(invest.getUid(), msg);
			}
		});
	}

	//添加资金记录
	public void addCapitalLog(int uid, Double tradeMoney, int pid, int type) {
		//添加资金记录
		CapitalLog capitalLog = new CapitalLog();
		capitalLog.setUid(uid);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
		capitalLog.setTradeDate(simpleDateFormat.format(new Date()));
		capitalLog.setTradeMoney(tradeMoney);
		capitalLog.setType(type);
		capitalLog.setRemark(pid + " 项目收益");
		otherService.addCapitalLog(capitalLog);
	}

	//更新用户余额
	public void upadteUserBalance(int id, Double balance) {
		otherService.updateUserBalance(id, balance);
	}

	//发送消息
	public void sendMsg(int uid, String msg) {
		Inform inform = new Inform();
		inform.setInformTitle("到期返利！");
		inform.setInformContent(msg);
		inform.setInformSenderId(AdminInformConstants.ADMIN_ID_LABEL);
		inform.setInformRecipientsId(uid);
		inform.setSendTime(System.currentTimeMillis());
		informService.saveInform(inform);
	}
}
